#include "Fans.h"
#include <EEPROM.h>

Fan::Fan( byte Pin, int MemLoc, pin_callback cb) {
	memLoc = MemLoc;
	pin = Pin;
	pinCtrl = cb;
	
}


void Fan::begin() {


	fanMode = (fanMode_t) EEPROM.read ( memLoc );

	if ( fanMode > fanAuto ) fanMode = fanOn;

	temp = EEPROM.read ( memLoc + 1);
	if ( fanMode == fanOn ) {
		toggleState( true );
	} else if ( fanMode == fanOff ) {
		toggleState( false );
	} 

}
void Fan::setMode( fanMode_t mode) {
	fanMode = mode;
	if ( fanMode == fanOn ) toggleState(true);
	else if ( fanMode == fanOff ) toggleState(false);
}

void Fan::save() {
	byte a = EEPROM.read ( memLoc);
	byte b = EEPROM.read ( memLoc + 1);
	if ( (fanMode_t) a != fanMode ) {
		Serial.print("Write Mode ");
		Serial.print(pin);
		Serial.print(" MEM: ");
		Serial.print(a);
		Serial.print(" NEW: ");
		Serial.println( fanMode );
		EEPROM.write ( memLoc, fanMode );
	}
	if ( b != temp ) {
		Serial.print("Write Temp ");
		Serial.println(pin);
		
		EEPROM.write ( memLoc + 1, temp );
	}
}

void Fan::setOnTemp( byte tmp ) {
	temp = tmp;
	}

byte Fan::getOnTemp( ) {
	return temp;
}

fanMode_t Fan::getMode() {
	//return fanOn;
	return (fanMode_t) fanMode;
}

void Fan::toggleState( boolean state ) {
	st = state;
	// write pin
	
	(*pinCtrl) ( pin, st );

}

boolean Fan::getState() {
	return st;

}